<?php

namespace app\nideshop\controller;

use think\Db;
use app\nideshop\validate\OrderValidate;
use app\nideshop\service\Token;

class Order extends Base
{
	protected $datas;
	protected $table = 'order';

	/**
	 * 提交订单
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-26T22:41:43+0800
	 * @return   [type]                   [description]
	 */
	public function submitAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new OrderValidate, 'submit', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$addressId = $this->datas['addressId'];
		$couponId = $this->datas['couponId'];
		$postscript = isset($this->datas['postscript']) ? $this->datas['postscript'] : '';
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
  		$checkedAddress = Db::name('address')->where('id', $addressId)->find();
  		if (empty($checkedAddress)) {
  			return json(['errno' => 400, 'errmsg' => '请选择收货地址', 'data' => []]);
  		}
  		$freightPrice = 0.00;
  		$checkedGoodsList = Db::name('cart')
	  		->where(['user_id' => $userId, 'session_id' => 1, 'checked' => 1 ])
	  		->select();
	    if (empty($checkedGoodsList)) {
	      	return json(['errno' => 400, 'errmsg' => '请选择商品', 'data' => []]);
	    }
	    // 统计商品总价
	    $goodsTotalPrice = 0.00;
	    foreach ($checkedGoodsList as $key => $value) {
	    	$goodsTotalPrice += $value['number'] * $value['retail_price'];
	    }
	    // 获取订单使用的优惠券
	    $couponPrice = 0.00;
	    if (!empty($couponId)) {

	    }
	    // 订单价格计算
	    $orderTotalPrice = $goodsTotalPrice + $freightPrice - $couponPrice; // 订单的总价
	    $actualPrice = $orderTotalPrice - 0.00; // 减去其它支付的金额后，要实际支付的金额
	    $currentTime = time();
	    $orderInfo = [
	    	'order_sn' => $this->createOrderNo(),
	    	'user_id' => $userId,
	    	// 收货地址和运费
	    	'consignee' => $checkedAddress['name'],
			'mobile' => $checkedAddress['mobile'],
			'province' => $checkedAddress['province_id'],
			'city' => $checkedAddress['city_id'],
			'district' => $checkedAddress['district_id'],
			'address' => $checkedAddress['address'],
			'freight_price' => 0.00,
			// 留言
      		'postscript' => $postscript,
      		// 使用的优惠券
			'coupon_id' => 0,
			'coupon_price' => $couponPrice,

			'add_time' => $currentTime,
			'goods_price' => $goodsTotalPrice,
			'order_price' => $orderTotalPrice,
			'actual_price' => $actualPrice
	    ];
	    $orderId = Db::name($this->table)->insertGetId($orderInfo);
	    if (!$orderId) {
	    	return json(['errno' => 400, 'errmsg' => '订单提交失败', 'data' => []]);
	    }
	    $orderGoodsData = [];
	    foreach ($checkedGoodsList as $key => $value) {
	    	$orderGoodsData[$key]['order_id'] = $orderId;
		    $orderGoodsData[$key]['goods_id'] = $value['goods_id'];
		    $orderGoodsData[$key]['goods_sn'] = $value['goods_sn'];
		    $orderGoodsData[$key]['product_id'] = $value['product_id'];
		    $orderGoodsData[$key]['goods_name'] = $value['goods_name'];
		    $orderGoodsData[$key]['list_pic_url'] = $value['list_pic_url'];
		    $orderGoodsData[$key]['market_price'] = $value['market_price'];
		    $orderGoodsData[$key]['retail_price'] = $value['retail_price'];
		    $orderGoodsData[$key]['number'] = $value['number'];
		    $orderGoodsData[$key]['goods_specifition_name_value'] = $value['goods_specifition_name_value'];
		    $orderGoodsData[$key]['goods_specifition_ids'] = $value['goods_specifition_ids'];
	    }
	    //事务
	    Db::startTrans();
		try {
		    Db::name('order_goods')->insertAll($orderGoodsData);
		    Db::name('cart')->where(['user_id' => $userId, 'session_id' => 1, 'checked' => 1])->delete();
		    Db::commit();
		} catch (\Exception $e) {
		    Db::rollback();
		    //删除订单
		    return json(['errno' => 400, 'errmsg' => '失败', 'data' => []]);
		}
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'orderInfo' => $orderInfo
			]
		]);
	}

	/**
	 * 订单列表
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-27T22:23:04+0800
	 * @return   [type]                   [description]
	 */
	public function listAction()
	{
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$orderObj = Db::name($this->table)
			->where('user_id', $userId)
			->paginate(10, false, ['page' => 1]);
		$orderList = $orderObj->items();
		foreach ($orderList as $key => $value) {
			$orderList[$key]['goodsList'] = Db::name('order_goods')->where('order_id', $value['id'])->select();
			$orderList[$key]['goodsCount'] = Db::name('order_goods')->where('order_id', $value['id'])->count('id'); //*数量
			$orderList[$key]['order_status_text'] = Db::name($this->table)
				->where('id', $value['id'])
				->value('if(order_status = 0, "未付款","已付款") statusText');
			$orderList[$key]['handleOption'] = [
				'cancel' => false, // 取消操作
				'delete' => false, // 删除操作
				'pay' => false, // 支付操作
				'comment' => false, // 评论操作
				'delivery' => false, // 确认收货操作
				'confirm' => false, // 完成订单操作
				'return' => false, // 退换货操作
				'buy' => false // 再次购买
			];
		}
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'count' => $orderObj->total(),
				'totalPages' => 0,
				'pageSize' => 10,
				'currentPage' => $orderObj->currentPage(), 
				'data' => $orderList
			]
		]);
	}

	/**
	 * 订单详情
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-27T23:41:06+0800
	 * @return   [type]                   [description]
	 */
	public function detailAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new OrderValidate, 'detail', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$orderId = $this->datas['orderId'];
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$orderInfo = Db::name($this->table)->where(['user_id' => $userId, 'id' => $orderId])->find();
		if (empty($orderInfo)) {
			return json(['errno' => 400, 'errmsg' => '订单不存在', 'data' => []]);
		}
		$orderInfo['province_name'] = Db::name('region')->where('id', $orderInfo['province'])->value('name');
	    $orderInfo['city_name'] = Db::name('region')->where('id', $orderInfo['city'])->value('name');
	    $orderInfo['district_name'] = Db::name('region')->where('id', $orderInfo['district'])->value('name');
	    $orderInfo['full_region'] = $orderInfo['province_name'] + $orderInfo['city_name'] + $orderInfo['district_name'];
	    $latestExpressInfo = $this->getLatestOrderExpress($orderId);
    	$orderInfo['express'] = $latestExpressInfo;
    	$orderGoods = Db::name('order_goods')->where('order_id', $orderId)->select();
    	// 订单状态的处理
	    $orderInfo['order_status_text'] = Db::name($this->table)
				->where('id', $orderId)
				->value('if(order_status = 0, "未付款","已付款") statusText');
	    $orderInfo['add_time'] = time();
	    $orderInfo['final_pay_time'] = time();
	    // 订单最后支付时间
	    if ($orderInfo['order_status'] === 0) {
	    	$orderInfo['final_pay_time'] = time();
	    }
	    // 订单可操作的选择,删除，支付，收货，评论，退换货
    	$handleOption = [
			'cancel' => false, // 取消操作
			'delete' => false, // 删除操作
			'pay' => false, // 支付操作
			'comment' => false, // 评论操作
			'delivery' => false, // 确认收货操作
			'confirm' => false, // 完成订单操作
			'return' => false, // 退换货操作
			'buy' => false // 再次购买
		];
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'orderInfo' => $orderInfo,
				'orderGoods' => $orderGoods,
				'handleOption' => $handleOption
			]
		]);
	}

	/**
	 * 获取最新订单快件
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-28T22:12:12+0800
	 * @param    [type]                   $orderId [description]
	 * @return   [type]                            [description]
	 */
	protected function getLatestOrderExpress($orderId)
	{
		$returnExpressInfo = [
			'shipper_code' => '',
			'shipper_name' => '',
			'logistic_code' => '',
			'is_finish' => 0,
			'request_time' => 0,
			'traces' => []
    	];
    	$orderExpress = Db::name('order_express')->where('order_id', $orderId)->find();
		if (empty($orderExpress)) {
			return $returnExpressInfo;
		}
		if (empty($orderExpress['shipper_code']) || empty($orderExpress['logistic_code'])) {
			return $returnExpressInfo;
		}
		$returnExpressInfo['shipper_code'] = $orderExpress['shipper_code'];
		$returnExpressInfo['shipper_name'] = $orderExpress['shipper_name'];
		$returnExpressInfo['logistic_code'] = $orderExpress['logistic_code'];
		$returnExpressInfo['is_finish'] = $orderExpress['is_finish'];
		$returnExpressInfo['request_time'] = time();
		$returnExpressInfo['traces'] = empty($orderExpress['traces']) ? [] : json_encode($orderExpress['traces']);
		// 如果物流配送已完成，直接返回
		if ($orderExpress['is_finish']) {
      		return $returnExpressInfo;
    	}
    	//
    	return $returnExpressInfo;
	}

	/**
	 * 取消订单
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-28T22:16:53+0800
	 * @return   [type]                   [description]
	 */
	public function cancelAction()
	{

	}

	/**
	 * 查询物流信息
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-28T22:17:21+0800
	 * @return   [type]                   [description]
	 */
	public function expressAction()
	{
		$this->datas = $this->params;
		$orderId = $this->datas['orderId'];
	    if (empty($orderId)) {
	      	return json(['errno' => 400, 'errmsg' => '订单不存在', 'data' => []]);
	    }
	    $latestExpressInfo = $this->getLatestOrderExpress($orderId);
	    return json([
	    	'errno' => 0,
			'errmsg' => '',
			'data' => $latestExpressInfo
	    ]);
	}
}